package yxy.game.pm2.command.dungeon;

import yxy.cherry.data.bean.bubblebattle;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.DungeonMessage;
import yxy.game.pm2.module.conquest.ConquestModule;
import yxy.game.pm2.module.dungeon.*;

/** 日常副本 副本挑战 */
@MessageType(proto = Command.DungeonChanllenge, classtype = DungeonMessage.DungeonChanllengeRequest.class)
public class CMD_DungeonChanllenge extends Command<DungeonMessage.DungeonChanllengeRequest> {

	@Override
	public void execute(MessageSource messageSource, DungeonMessage.DungeonChanllengeRequest request) {
		String playerCode = messageSource.getTag();
		int dungeonId = request.getId();

		DungeonMessage.DungeonChanllengeResponse.Builder response = DungeonMessage.DungeonChanllengeResponse.newBuilder();

		DungeonHandle handle = new DungeonHandle();
		if (handle.isBattling(playerCode)) {
			send(messageSource, response, Result.BattleIsRunning);// 还有正在进行中的战斗
			return;
		}

		// 判断是否可挑战
		bubblebattle _data = DungeonHandle.data(dungeonId);
		DungeonModule module = DungeonModule.get(playerCode, DungeonType.forNumber(_data.getType()));
		if (module == null || !module.isOpen()) {
			send(messageSource, response, Result.ModuleNotOpen);// 副本尚未开启
			return;
		}

		DungeonStage stage = module.stage(dungeonId);
		if (stage == null || !stage.getState().equals(DungeonStageState.可挑战)) {
			send(messageSource, response, Result.DungeonCantChanllenge);// 关卡尚不能挑战
			return;
		}

		// 判断等级
		PlayerBean player = PlayerBean.get(playerCode);
		if (player.getLevel() < _data.getLeave()) {
			send(messageSource, response, Result.DungeonChanllengeLowLevel);// 主公等级不够
			return;
		}

		// 判断征战关卡
		ConquestModule conquestModule = ConquestModule.get(playerCode);
		if (conquestModule.getMapId() < _data.getDps()) {
			send(messageSource, response, Result.DungeonChanllengeLowMap);// 主公征战关卡没达到条件
			return;
		}

		try {
			response.setBattle(handle.battleResponse(playerCode, _data));
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, DungeonMessage.DungeonChanllengeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}